import window from '@ohos.window'
import HashMap from '@ohos.util.HashMap'
import JsDataStore from './JsDataStore'
import JsLogger from './JsLogger'
import { JsWindow } from './JsWindow'

export class JsWindowManager {
    private windows: HashMap<string, JsWindow> = new HashMap;

    constructor() {

    }


    async addWindow(name: string, window: JsWindow) : Promise<void> {
        if (this.windows.hasKey(name))
            return;
        this.windows.set(name, window)
        JsDataStore.getJsObjectLoader().addJsObject(name, window);
    }

     async createWindow(name: string): Promise<boolean> {
         try {
             if (this.windows.hasKey(name))
                 return false;
             let windowStage = JsDataStore.getWindowStage();
             let windowClass = await windowStage.createSubWindow(name);
             let window = new JsWindow(name, windowClass);
             await window.load();
             this.addWindow(name, window);
             return true;
         } catch (e) {
             JsLogger.error("create window failed %{public}s", JSON.stringify(e));
             return false;
         }
    }

    async destroyWindow(name: string): Promise<boolean> {
        if (!this.windows.hasKey(name))
            return false;
        let window = this.windows.get(name);
        let result =await window.destroyWindow();
        JsDataStore.getJsObjectLoader().deleteJsObject(name);
        return result;
    }
}
